/*
 * ObjectGenerate.java
 *
 * Created on 31 de Agosto de 2007, 19:19
 *
 */

package util;

import java.util.Date;
import bd.SqlGenerate;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 *
 * @author Evolution Systems - Do the Evolution!!
 */
public class ObjectGenerate {
    
    /** Creates a new instance of ObjectGenerate */
   public ObjectGenerate() 
   {
        
    }
    
   public String objectJavaGenerate(String namePackage, String name, String fields[], String types[])
   {
        String class_object, sql = "";
        String [] whereField, whereTypeField;
        Date dateTime = new Date();
         
        class_object = "/*obj"+name+".java\n"
            +"*\n"
            +"* Created on "+dateTime.toString()+"\n"
            +"*\n"
            +"*/\n"
            +"\npackage "+namePackage+";\n\n"
            +"import javax.swing.JOptionPane;\n"
            + "import java.sql.*; \n\n"
                
            /*Bibliotec temporary*/
            +"import common.*;\n"
                
        +"public class "+name+" \n "
        + "{ \n\n"

                + "\t\t public "+name+" (Database database)\n "
                + "\t\t {\n\n "
                    +"\t\t\t this.database = database; \n"
                + "\t\t }\n\n "

                + "\t\t /*Atributes*/\n\n "
                + "\t\t private Database database;\n"
                + "\t\t private ResultSet resultset; \n";
        
        for(int i=0; i < fields.length; i++)
            class_object +="\t\t private " + types[i] + " " + fields[i] + ";\n" ; 
        
        class_object +=
                 "\n\n\t\t /*Properties*/\n\n ";

        for(int i=0; i < fields.length; i++)
        {          
            class_object +="\t\t public void set" + fields[i] + " (" + types[i] + " value)\n "
                          +"\t\t{ \n"
                                +"\t\t\t this." + fields[i] + " = value; \n"
                          +"\t\t}\n\n";
            
            class_object +="\t\t public "+ types[i] + " get" +fields[i] + "()\n"     
                          +"\t\t{ \n"
                                +"\t\t\t return this."+ fields[i] + "; \n"
                          +"\t\t}\n\n";
        }              
        
        class_object +=
               "\n\n\t\t /*Methods*/\n\n "

    
    /* Building the Get method;             */
                + "\t\t public boolean Get()\n "
                + "\t\t {\n\n "
                        +"\t\t\t String sql;\n"
                        + "\t\t\t try \n"                
                        + "\t\t\t { \n";
        
                            whereField=new String [1];
                            whereField[0]=fields[0];
                        
                            whereTypeField=new String [1];
                            whereTypeField[0]=types[0];
                        
                            sql = SqlGenerate.Select(name, fields, whereField, whereTypeField );
        
        class_object +="\t\t\t\t sql = " + sql + ";\n"                
                     + "\t\t\t\t resultset = database.executeQueryRs(sql);\n"
                     + "\t\t\t\t resultset.next();\n"                ;
        /*TODO: Test all fields of all databases*/
        for(int i=1; i < fields.length; i++)
        {
           if( types[i].equals("int"))
               class_object +="\t\t\t\t " + fields[i] + "= resultset.getInt(\"" + fields[i] + "\");\n";
           else if(types[i].equals("double")) 
               class_object +="\t\t\t\t " + fields[i] + "= resultset.getDouble(\"" + fields[i] + "\");\n";
           else if(types[i].equals ("boolean"))
              class_object +="\t\t\t\t " + fields[i] + "= resultset.getBoolean(\"" + fields[i] + "\");\n";
           else
              class_object +="\t\t\t\t " + fields[i] + "= resultset.getString(\"" + fields[i] + "\");\n";
        }
        
        class_object +="\t\t\t\t return true; \n"
                     + "\t\t\t } \n"
                     + "\t\t\t catch(Exception ex) \n "
                     + "\t\t\t { \n"
                     + "\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + ex); \n" 
                     + "\t\t\t\t return false; \n"
                     + "\t\t\t } \n"
                     +"\t\t }\n\n ";
    
    /* Building the Save method;              */
       class_object +="\t\t public boolean Save()\n "
                    + "\t\t {\n\n "
                        +"\t\t\t String sql;\n"
                        +"\t\t\t try \n"                
                        + "\t\t\t { \n";
        
                        sql = SqlGenerate.Insert(name, fields, types);

      class_object +="\t\t\t\t sql = " + sql + ";\n"                
                     + "\t\t\t\t database.executeCommand(sql, database.doNotUseTransaction);\n"
                     +"\t\t\t\t if (database.Error) \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + database.ErrorMessage); \n" 
                        +"\t\t\t\t\t return false; \n"               
                     +"\t\t\t\t } \n"
                     +"\t\t\t\t else \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o efetuada com sucesso! \" ); \n" 
                        +"\t\t\t\t\t return true; \n"               
                     +"\t\t\t\t } \n"    
                     + "\t\t\t } \n"
                     + "\t\t\t catch(Exception ex) \n "
                     + "\t\t\t { \n"
                     + "\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + ex); \n" 
                     + "\t\t\t\t return false; \n"
                     + "\t\t\t } \n"
                     +"\t\t }\n\n ";
   
    
    /* Building the Update method;              */
      class_object += "\t\t public boolean Update()\n "
                    + "\t\t {\n\n "
                        +"\t\t\t String sql;\n"
                        +"\t\t\t try \n"                
                        + "\t\t\t { \n";
        
                        sql = SqlGenerate.Update(name, fields, types);

      class_object +="\t\t\t\t sql = " + sql + ";\n"                
                     + "\t\t\t\t database.executeCommand(sql, database.doNotUseTransaction);\n"
                     +"\t\t\t\t if (database.Error) \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + database.ErrorMessage); \n" 
                        +"\t\t\t\t\t return false; \n"               
                     +"\t\t\t\t } \n"
                     +"\t\t\t\t else \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o efetuada com sucesso! \" ); \n" 
                        +"\t\t\t\t\t return true; \n"               
                     +"\t\t\t\t } \n"    
                     + "\t\t\t } \n"
                     + "\t\t\t catch(Exception ex) \n "
                     + "\t\t\t { \n"
                     + "\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + ex); \n" 
                     + "\t\t\t\t return false; \n"
                     + "\t\t\t } \n"
                     +"\t\t }\n\n ";
    
    /* Building the Delete method;               */
      class_object += "\t\t public boolean Delete()\n "
                    + "\t\t {\n\n "
                        +"\t\t\t String sql;\n"
                        +"\t\t\t try \n"                
                        + "\t\t\t { \n";
        
                        sql = SqlGenerate.Delete(name, fields, types);

      class_object +="\t\t\t\t sql = " + sql + ";\n"                
                     + "\t\t\t\t database.executeCommand(sql, database.doNotUseTransaction);\n"
                     +"\t\t\t\t if (database.Error) \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + database.ErrorMessage); \n" 
                        +"\t\t\t\t\t return false; \n"               
                     +"\t\t\t\t } \n"
                     +"\t\t\t\t else \n"
                     +"\t\t\t\t { \n"
                        +"\t\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o efetuada com sucesso! \" ); \n" 
                        +"\t\t\t\t\t return true; \n"               
                     +"\t\t\t\t } \n"    
                     + "\t\t\t } \n"
                     + "\t\t\t catch(Exception ex) \n "
                     + "\t\t\t { \n"
                     + "\t\t\t\t JOptionPane.showMessageDialog(null, \"Opera��o n�o pode ser executada!\" + \"\\n\" + ex); \n" 
                     + "\t\t\t\t return false; \n"
                     + "\t\t\t } \n"
                     +"\t\t }\n\n ";

    /* Building the Search method;              */
       class_object +="\t\t public DataSet Search()\n "
                    + "\t\t {\n\n "
                        +"\t\t\t DataSet ds;\n"               
                        +"\t\t\t String sql;\n"
                        +"\t\t\t try \n"                
                        + "\t\t\t { \n";
                            
                            whereField=new String [0];                       
                            whereTypeField=new String [0];
                        
                        sql = SqlGenerate.Select(name, fields, whereField, whereTypeField );        

      class_object +="\t\t\t\t sql = " + sql + ";\n"                
                     + "\t\t\t\t ds = database.executeQuery(sql);\n"
                     +"\t\t\t\t if (database.Error) \n"
                     +"\t\t\t\t { \n" 
                        +"\t\t\t\t\t return null; \n"               
                     +"\t\t\t\t } \n"
                     +"\t\t\t\t else \n"
                     +"\t\t\t\t { \n" 
                        +"\t\t\t\t\t return ds; \n"               
                     +"\t\t\t\t } \n"    
                     + "\t\t\t } \n"
                     + "\t\t\t catch(Exception ex) \n "
                     + "\t\t\t { \n"
                     + "\t\t\t\t return null; \n"
                     + "\t\t\t } \n"
                     +"\t\t }\n\n "
        + "} ";
        
        return class_object;
    }
    
   public String objectDelphiGenerate(String name, String fields[], String types[])
   {
      String class_object;
      Date dateTime = new Date();
        
      class_object= 
         "{*"+name+".pas\n"
         +"*\n"
         +"* Created on "+dateTime.toString()+"\n"
         +"*\n"
         +"*}\n\n"         
         
         +"unit U_"+name+";\n\n"

         +"interface\n\n"

         +"uses\n"
         +"ADODB, SysUtils, U_GenerateSql, Forms, Windows, UConstante;\n\n"

         +"type\n"
         +"\tT"+name+"=class\n"
         +"\tprivate\n";
      
         for(int i=0; i < fields.length; i++)
            class_object +="\t\tt" + fields[i] + " : " + types[i] + ";\n" ; 
      
         class_object+= 
          "\t\tadoConnection: TADOConnection;\n"
         +"\t\tqryCliente : TADOQuery;\n\n"

         +"\t\tprocedure SetClass;\n"
         +"\tpublic\n"
         +"\t\tconstructor Create();\n"
         +"\t\tdestructor Destroy();\n"
         +"\t\tprocedure SetConnection(AdoCon :TADOConnection);\n"
         +"\t\tprocedure Clear();\n\n"

         +"\t\tfunction GetClass (Id : string = '') : boolean;\n"
         +"\t\tfunction Save(TipoOperacao : string = 'I'; UsaTransacao : boolean = false) : boolean;\n"
         +"\t\tfunction Delete(Id : string = ''; UsaTransacao : boolean = false) : boolean;\n\n"

         +"\t\tfunction GetNextId() : string;\n"
         +"\t\tfunction GetLastId : string;\n\n"

         +"\tpublished\n";
         for(int i=0; i < fields.length; i++)
            class_object +="\t\tproperty " + fields[i] + " : " + types[i] + " read t"+fields[i]+"\t write t"+fields[i]+";\n" ; 
         
         class_object+= 
          "\n\t\tproperty Connection          : TADOConnection        read adoConnection         write adoConnection;\n"
         +"\t\tproperty Query               : TADOQuery             read qryCliente           write qryCliente;\n\n"

         +"end;\n\n"

         +"implementation\n\n"

         +"uses DB;\n\n"

         +"{ "+name+" }\n\n"

         //Clear();
         +"procedure T"+name+".Clear();\n"
         +"begin\n";
         for(int i=0; i < fields.length; i++)
            class_object +="\tt" + fields[i] + " := '';\n";             
         
         class_object+= "end;\n\n\n"

         //Create();
         +"constructor T"+name+".Create();\n"
         +"begin\n"
         +"end;\n\n\n"

         //Delete();
         +"function T"+name+".Delete(Id: string; UsaTransacao: boolean): boolean;\n"
         +"var\n"
            +"\tgSql: TUsaGenerateSql;\n"
         +"begin\n"
            +"\tif (Id = '') then Id := t"+fields[0]+"\n"
            +"\tgSql := TUsaGenerateSql.Create(Application);\n"
            +"\ttry\n"
            +"\t\tgSql.Prepare;\n"
            +"\t\tgSql.SQLConnection := adoConnection;\n"
            +"\t\tgSql.Tabela := '"+name+"';\n"
            +"\t\tgSql.CommandType := cmdDelete;\n"
            +"\t\tgSql.CondicaoWhere.Add('("+fields[0]+" ='+QuotedStr(Id)+')');\n"
            +"\t\tif not gSql.Execute then\n"
            +"\t\t\traise Exception.Create(gSql.GetMessageErro);\n"
            +"\t\tresult := true;\n"
            +"\texcept\n"
            +"\t\ton Erro:Exception do\n"
            +"\t\tbegin\n"
            +"\t\t\tApplication.MessageBox(PChar('Ocorreu um erro na deleção dos dados.'+#13+#13+'Código do Erro: ' + Erro.Message), '"+name+"', MB_ICONERROR);\n"
            +"\t\t\tresult := false;\n"
            +"\t\tend;\n"
            +"\tend;\n"
            +"\tgSql.Free();\n"
         +"end;\n\n\n"

         +"destructor T"+name+".Destroy();\n"
         +"begin\n"
            +"\tqryCliente.Free();\n"
         +"end;\n\n\n"

         //GetClass();
         +"function T"+name+".GetClass(Id: string): boolean;\n"
         +"var\n"
            +"\t\tsSql : string;\n"
         +"begin\n"
            +"\tif (Id = '') then Id := t"+fields[0]+";\n\n"

            +"\tsSql := 'SELECT '\n"
                +"\t\t+ '* '\n"
                +"\t\t+ 'FROM '\n"
                +"\t\t+ 'cliente '\n"
                +"\t\t+ 'WHERE '\n"
                +"\t\t+ '("+fields[0]+" = ' + QuotedStr(Id) + ') ';\n\n"

            +"\tqryCliente.Close();\n"
            +"\tqryCliente.SQL.Clear;\n"
            +"\tqryCliente.SQL.Add(sSQl);\n"
            +"\tqryCliente.Open();\n\n"

            +"\tresult := (not qryCliente.IsEmpty());\n\n"

            +"\tif result then SetClass();\n\n"

         +"end;\n\n\n"

         //GetLastId();
         +"function T"+name+".GetLastId: string;\n"
         +"var\n"
            +"\tsSql : string;\n"
            +"\tqryTemp : TAdoQuery;\n"
         +"begin\n"
         +"\tresult := '0';\n"
         +"\tqryTemp := TADOQuery.Create(Application);\n"
         +"\tqryTemp.Connection := adoConnection;\n"
         +"\ttry\n"
            +"\t\tsSql := 'SELECT '\n"
                  +"\t\t\t+ 'last_value '\n"
                  +"\t\t\t+ 'FROM '\n"
                  +"\t\t\t+ '"+name+"_"+fields[0]+"_seq ';\n\n"

            +"\t\tqryTemp.SQL.Add(sSQl);\n"
            +"\t\tqryTemp.Open();\n\n"

            +"\t\tresult := qryTemp.FieldByName('last_value').AsString;\n"
         +"\tfinally\n"
         +"\t\tqryTemp.Free();\n"
         +"\tend;\n"

         +"end;\n\n\n"

         //GetNextId();
         +"function T"+name+".GetNextId: string;\n"
         +"var\n"
            +"\tsSql : string;\n"
            +"\tqryTemp : TAdoQuery;\n"
         +"begin\n"
         +"\tresult := '0';\n"
         +"\tqryTemp := TADOQuery.Create(Application);\n"
         +"\tqryTemp.Connection := adoConnection;\n"
         +"\ttry\n"
            +"\t\tsSql := 'SELECT '\n"
               +"\t\t\t+ '(last_value + 1) as next_id '\n"
               +"\t\t\t+ 'FROM '\n"
               +"\t\t\t+ '"+name+"_"+fields[0]+"_seq ';\n"

         +"\t\tqryTemp.SQL.Add(sSQl);\n"
         +"\t\tqryTemp.Open();\n\n"

         +"\t\tresult := qryTemp.FieldByName('next_id').AsString;\n"
         +"\tfinally\n"
         +"\t\tqryTemp.Free();\n"
         +"\tend;\n"
         +"end;\n\n\n"

         //Save();
         +"function T"+name+".Save(TipoOperacao: string; UsaTransacao: boolean): boolean;\n"
         +"var\n"
         +"\tgSql : TUsaGenerateSql;\n"
         +"begin\n"
            +"\tgSql := TUsaGenerateSql.Create(Application);\n"
            +"\ttry\n"
            +"\t\tgSql.Prepare();\n"
            +"\t\tgSql.SQLConnection := adoConnection;\n"
            +"\t\tgSql.Tabela := '"+name+"';\n\n"

            +"\t\t//--- INSERT\n"
            +"\t\tif (TipoOperacao = 'I') then gSql.CommandType := cmdInsert\n\n"

            +"\t\t//--- UPDATE\n"
            +"\t\telse\n"
            +"\t\tbegin\n"
            +"\t\t\tgSql.CommandType := cmdUpDate;\n"
            +"\t\t\tgSql.CondicaoWhere.Add('("+fields[0]+" = '+QuotedStr(t"+fields[0]+")+')');\n"
            +"\t\tend;\n\n";

            for(int i=0; i < fields.length; i++)
               class_object +="\t\tgSql.SetValue(t"+fields[i]+", '"+fields[i]+"');\n";

            class_object+=
             "\t\tif not gSql.Execute(UsaTransacao) then\n"
            +"\t\traise Exception.Create(gSql.GetMessageErro);\n"
            +"\t\tresult := true;\n\n"

            +"\t\tif (TipoOperacao = 'I') then t"+fields[0]+" := GetLastId;\n\n"

         +"\tExcept\n"
         +"\t\ton Erro:Exception do\n"
         +"\t\tbegin\n"
         +"\t\t\tApplication.MessageBox(PChar('Ocorreu um erro na gravação dos dados.'+#13+#13+'Código do Erro: ' + Erro.Message), '"+name+"', MB_ICONERROR);\n"
         +"\t\t\tresult := false;\n"
         +"\t\tend;\n"
         +"\tend;\n"
         +"\tgSql.Free();\n"

         +"end;\n\n\n"

         //SetClass();
         +"procedure T"+name+".SetClass();\n"
         +"begin\n"
            +"\tClear();\n"
            +"\tif (qryCliente.IsEmpty()) then exit;\n\n";

         for(int i=0; i < fields.length; i++)
            class_object +="\tt"+fields[i]+" := qryCliente.FieldByName('"+fields[i]+"').As"+types[i]+";\n";
               
         class_object+= "end;\n\n\n"

         //SetConnection();
         +"procedure T"+name+".SetConnection(AdoCon: TADOConnection);\n"
         +"begin\n"
            +"\tadoConnection := AdoCon;\n"
            +"\tqryCliente := TADOQuery.Create(nil); \n"
            +"\tqryCliente.Connection := AdoCon;\n"
         +"end;\n\n"

         +"end.";
         
        return class_object;
   }

   public String objectCsharpGenerate(String namespace, String name, String fields[], String labels[], 
                                String lengthFields[], String types[])
   {
      String form, aux;
      String objectName = name.toLowerCase();
      int i;
      
      form = "";
      aux = "";
      try 
      {
         BufferedReader in = new BufferedReader(new FileReader("res/templates/C#/RegisterTemplate/Object.cs"));
         while (in.ready()) 
           form += in.readLine()+"\n";
         in.close();
      } 
      catch (IOException e) 
      {
      }       
      
      //Namespace
      form = form.replace("{NAMESPACE}", namespace);
      
      //Name of Form
      form = form.replace("{NAME}", name);
      
      //PRivate Declarations
      for (i=0; i < fields.length; i++)
      {
         //Retira o nome da tabela do inicio do nome
         aux+= "\t\tprivate string "+fields[i].replace(objectName, "")+";\n";
      }
      form = form.replace("{OBJECTPRIVATEDECLARATION}", aux);
      
      //Object constructor
      aux = "\t\t\tclear();\n";
      aux = "\t\t\tgsql.table= \""+objectName+"\";\n";
      aux+= "\t\t\t_sequence = \""+objectName+"_"+objectName+"_id_seq\";\n";
      form = form.replace("{OBJECTCONSTRUCTOR}", aux);
      
      //Object Properties
      aux = "";
      for (i=0; i < fields.length; i++)
      {
         //Retira o nome da tabela do inicio do nome da propriedade
         aux += "\t\tpublic string "+fields[i].replace(objectName+"_","")+"\n";
         aux += "\t\t{\n";
         aux += "\t\t\tget { return "+fields[i].replace(objectName, "")+";}\n";
         aux += "\t\t\tset { "+fields[i].replace(objectName, "")+"= value;}\n";
         aux += "\t\t}\n\n";
      }
      form = form.replace("{OBJECTPROPERTIES}", aux);
      
      //Object Clear
      aux = "";
      for (i=0; i < fields.length; i++)
      {
         aux+= "\t\t\t"+fields[i].replace(objectName, "")+"= string.Empty;\n";
      }
      form = form.replace("{OBJECTCLEAR}", aux);
      
      //Object get
      aux = "";
      for (i=0; i < fields.length; i++)
      {
         aux+= "\t\t\t"+fields[i].replace(objectName, "")+"= dr[\""+fields[i]+"\"].ToString();\n";
      }
      form = form.replace("{OBJECTGET}", aux);
      
      //Object setgsql
      aux = "";
      for (i=0; i < fields.length; i++)
      {
         aux+= "\t\t\tgsql.setValue("+fields[i].replace(objectName, "")+",\""+fields[i]+"\");\n";
      }
      form = form.replace("{OBJECTSETGSQL}", aux);      
      
      //List Constructor
      aux = "";
      aux = "gsql.table = \""+name+"\";";
      form = form.replace("{LISTCONSTRUCTOR}", aux);
      
      return form;
    }
}
